package com.geeksaga.service;

import java.util.StringTokenizer;

import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.WebRequest;

import com.geeksaga.dao.UserDao;
import com.geeksaga.domain.User;

/**
 * @author newbie
 * @since 0.1
 */
@Service
public class AuthorityService implements UserDetailsService {
	
	private static final Log logger = LogFactory.getLog(AuthorityService.class);
	
    @Autowired protected UserDao userDao;
    
    /**
     * @param userDao
     */
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    
    /* (non-Javadoc)
     * @see org.springframework.security.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
     */
	public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException, DataAccessException {

		StringTokenizer st = new StringTokenizer(userId, "___");
		User user = new User();
		user.setUserId(st.nextToken());
		user.setPid(st.nextToken());

        User authenticateUser = null;
        
		try {
			authenticateUser = userDao.authenticate(user);
		} catch (Exception e) {
			logger.info(e.getMessage(), e);
		}
		
        return (authenticateUser == null) ? new User() : authenticateUser;
    }
    
    /**
     * @param object
     * @return
     */
    public static User getUser(Object object) {
        SecurityContextImpl securityContextImpl= (SecurityContextImpl) ((HttpSession) object).getAttribute("SPRING_SECURITY_CONTEXT");
        
        if(securityContextImpl == null)
            return new User();
        
        Authentication authentication = securityContextImpl.getAuthentication();
        
        return (User) authentication.getPrincipal();
    }
    
    /**
     * @param request
     * @return
     */
    public static User getUser(WebRequest request) {
    	SecurityContextImpl securityContextImpl= (SecurityContextImpl) request.getAttribute("SPRING_SECURITY_CONTEXT", WebRequest.SCOPE_SESSION);
    	
    	if(securityContextImpl == null) {
    		return new User();
    	}
    	
    	Authentication authentication = securityContextImpl.getAuthentication();
    	
    	return (User) authentication.getPrincipal();
    }
    
    /**
     * @param session
     * @return
     */
    public static User getUser(HttpSession session) {
    	SecurityContextImpl securityContextImpl= (SecurityContextImpl) session.getAttribute("SPRING_SECURITY_CONTEXT");
    	
    	if(securityContextImpl == null) {
    		return new User();
    	}
    	
    	Authentication authentication = securityContextImpl.getAuthentication();
    	
    	return (User) authentication.getPrincipal();
    }    
}